<template>
  <div class="excel-import-container">
    <div class="action-bar">
      <el-button type="primary" @click="importExcel">导入Excel</el-button>
      <el-button type="success" @click="exportExcel"
        :disabled="activeTab === '' || sheetsData[activeTab]?.length === 0">
        导出当前Sheet
      </el-button>
    </div>

    <el-tabs v-model="activeTab" type="card" v-if="activeTab !== ''">
      <el-tab-pane v-for="(sheet, name) in sheetsData" :key="name" :label="name" :name="name">
        <!-- 添加显示行数控制 -->
        <div class="display-control">
          <span>已显示: {{ displayedRowCount[name] || 1 }} / {{ sheet.data.length }} 行</span>
        </div>

        <el-table :data="getDisplayedData(name)" border highlight-current-row style="overflow-x: auto; margin-top: 10px"
          max-height="600">
          <el-table-column v-for="(header, index) in sheet.headers" :key="index" :prop="header" :label="header"
            :min-width="120">
            <template #default="scope">
              <el-input v-model="scope.row[header]" @change="handleCellEdit(name, scope.row, header)"
                @keydown.enter.native="handleInputEnter(scope.$index, index, name, $event)"
                :ref="el => setInputRef(el, name, scope.$index, index)" />
            </template>
          </el-table-column>

          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button size="small" type="danger" @click="handleDelete(name, scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <div v-else class="empty-tips">
      <el-empty description="请导入Excel文件" />
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue';
import * as XLSX from 'xlsx';
import ExcelJS from 'exceljs';
import { saveAs } from 'file-saver';
import { ElMessage } from 'element-plus';

const activeTab = ref('');
const sheetsData = ref({});
const inputRefs = ref({});
const displayedRowCount = ref({}); // 记录每个sheet显示的行数

// 获取当前显示的数据（只返回已显示的行）
const getDisplayedData = (sheetName) => {
  if (!sheetsData.value[sheetName]) return [];
  const count = displayedRowCount.value[sheetName] || 1;
  return sheetsData.value[sheetName].data.slice(0, count);
};

// 设置输入框引用
const setInputRef = (el, sheetName, rowIndex, colIndex) => {
  if (!inputRefs.value[sheetName]) {
    inputRefs.value[sheetName] = {};
  }
  if (!inputRefs.value[sheetName][rowIndex]) {
    inputRefs.value[sheetName][rowIndex] = {};
  }
  inputRefs.value[sheetName][rowIndex][colIndex] = el;
};

// 处理回车键事件
const handleInputEnter = (rowIndex, colIndex, sheetName, event) => {
  event.preventDefault();

  const currentSheet = sheetsData.value[sheetName];
  if (!currentSheet) return;

  // 当前是最后显示的行，且还有更多数据未显示
  if (rowIndex === (displayedRowCount.value[sheetName] || 1) - 1 &&
    rowIndex < currentSheet.data.length - 1) {

    // 增加显示行数
    if (!displayedRowCount.value[sheetName]) {
      displayedRowCount.value[sheetName] = 1;
    }
    displayedRowCount.value[sheetName]++;

    nextTick(() => {
      // 聚焦到新显示行的同一列
      const nextInput = inputRefs.value[sheetName]?.[rowIndex + 1]?.[colIndex]?.$el?.querySelector('input');
      if (nextInput) {
        nextInput.focus();
        nextInput.select();
      }
    });
  }
  // 如果不是最后显示的行，直接跳转到下一行同一列
  else if (rowIndex < (displayedRowCount.value[sheetName] || 1) - 1) {
    nextTick(() => {
      const nextInput = inputRefs.value[sheetName]?.[rowIndex + 1]?.[colIndex]?.$el?.querySelector('input');
      if (nextInput) {
        nextInput.focus();
        nextInput.select();
      }
    });
  } else {
    ElMessage.primary(`您已到达最后一行`);
  }
};

// 导入Excel时重置显示行数
const importExcel = async () => {
  try {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xlsx, .xls';

    input.onchange = async (e) => {
      const file = e.target.files[0];
      if (!file) return;

      const data = await readExcel(file);
      if (Object.keys(data).length > 0) {
        sheetsData.value = data;
        activeTab.value = Object.keys(data)[0];
        // 重置显示行数为1
        displayedRowCount.value = {};
        Object.keys(data).forEach(name => {
          displayedRowCount.value[name] = 1;
        });
        ElMessage.success(`导入成功，共 ${Object.keys(data).length} 个Sheet`);
      }
    };

    input.click();
  } catch (error) {
    ElMessage.error(`导入失败: ${error.message}`);
  }
};

// 其他原有方法保持不变...
const readExcel = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const result = {};

        workbook.SheetNames.forEach(sheetName => {
          const worksheet = workbook.Sheets[sheetName];
          const jsonData = XLSX.utils.sheet_to_json(worksheet);

          if (jsonData.length > 0) {
            result[sheetName] = {
              headers: Object.keys(jsonData[0]),
              data: jsonData
            };
          }
        });

        resolve(result);
      } catch (error) {
        reject(error);
      }
    };
    reader.onerror = (error) => reject(error);
    reader.readAsArrayBuffer(file);
  });
};

const exportExcel = async () => {
  try {
    if (!activeTab.value || !sheetsData.value[activeTab.value]) return;

    const currentSheet = sheetsData.value[activeTab.value];

    // 1. 创建 workbook 和 worksheet
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet(activeTab.value);

    // 2. 设置全局字体为 Arial 10号
    worksheet.properties.defaultFont = {
      name: 'Arial',
      size: 10
    };

    // 3. 转换数据并设置表头
    if (currentSheet.data.length > 0) {
      // 获取第一个对象的键作为表头
      const headers = Object.keys(currentSheet.data[0]);

      // 添加表头行（带样式）
      const headerRow = worksheet.addRow(headers);
      headerRow.font = { bold: true, name: 'Arial', size: 10 };

      // 添加数据行
      currentSheet.data.forEach(item => {
        const rowData = headers.map(header => item[header]);
        worksheet.addRow(rowData);
      });

      worksheet.columns.forEach(column => {
        if (!column.values) return;
        const maxLength = column.values
          .map(v => v?.toString().length*1.2 || 0)
          .reduce((a, b) => Math.max(a, b), 0);
        column.width = Math.max(10, Math.min(maxLength + 2, 50)); // 限制最大50字符
      });
    }

    // 4. 导出文件（兼容浏览器和Node环境）
    const fileName = `${activeTab.value}_exported.xlsx`;

    if (typeof window === 'undefined') {
      // Node.js 环境
      await workbook.xlsx.writeFile(fileName);
    } else {
      // 浏览器环境
      const buffer = await workbook.xlsx.writeBuffer();
      saveAs(new Blob([buffer], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      }), fileName);
    }

    ElMessage.success(`"${activeTab.value}" Sheet导出成功`);
  } catch (error) {
    ElMessage.error(`导出失败: ${error instanceof Error ? error.message : String(error)}`);
  }
};

const handleCellEdit = (sheetName, row, header) => {
  console.log(`[${sheetName}] 单元格编辑: ${header} = ${row[header]}`);
};

const handleDelete = (sheetName, index) => {
  sheetsData.value[sheetName].data.splice(index, 1);
  ElMessage.success(`"${sheetName}" Sheet删除成功`);
};
</script>

<style scoped>
.excel-import-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.empty-tips {
  margin-top: 50px;
  text-align: center;
}

.display-control {
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}
</style>